package com.lingjtx.common.core.algorithm;

import com.lingjtx.common.core.constant.Const;
import com.lingjtx.common.core.util.CommonUtil;
import com.lingjtx.common.core.util.StringUtil;

public enum Algorithm {

    UUID("getUuid"),

    BASE64("getBase64"),

    TOKEN("getToken"),

    TIMESTAMP("getTimestamp"),

    RANDOM("getRandomString");

    private String name;

    Algorithm(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public final String toString() {
        try {
            return (String) Algorithm.class.getDeclaredMethod(getName()).invoke(Algorithm.this);
        } catch (Exception e) {
            return StringUtil.getUuid();
        }
    }

    private String getUuid() {
        return StringUtil.getUuid();
    }

    private String getBase64() {
        return CommonUtil.getBasicAuth(java.util.UUID.randomUUID().toString(), StringUtil.randomString(16));
    }

    private String getToken() {
        return AESUtil.encrypt(getUuid(), Const.MD5_SALT)
                .replace("+", "-")
                .replace("/", "_")
                .replace("=", ".");
    }

    private String getTimestamp() {
        return String.valueOf(System.currentTimeMillis());
    }

    private static final char[] CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
            'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E',
            'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_'};

    public String getRandomString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            sb.append(CHARS[CommonUtil.randomScope(0, 63)]);
        }
        return sb.toString();
    }
}
